﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Small.Express
{
   public  class BaseExpress
    {

        /// <summary>
        /// 获取到表达值中名称
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="express"></param>
        /// <returns></returns>
        public static ExpressItem GetExpressName<T>(Expression<Func<T, object>> express)
        {

            ExpressItem expressItem = new ExpressItem();


            if (express == null) { return null; }

            var expressText = express.Body.ToString();
            var desc = ".Desc(";
            if (expressText.Contains(desc))
            {
                var firstIndex = expressText.IndexOf(".");
                if (firstIndex == -1) { return null; }
                var descIndex = expressText.IndexOf(desc);
                var name = expressText.Substring(firstIndex + 1, descIndex - firstIndex - 1);

                var first1 = expressText.IndexOf("\"");
                var last1 = expressText.LastIndexOf("\"");
                var value = expressText.Substring(first1 + 1, last1 - first1 - 1);

                expressItem.Text = name.Replace(")", "").Replace(")", "");
                expressItem.Value = value;

            }
            else
            {
                var index = expressText.LastIndexOf(".");

                if (index > 0)
                {
                    expressText = expressText.Substring(index + 1, (expressText.Length - index - 1));
                    expressText = expressText.Replace(")", "");
                    expressItem.Text = expressText;
                    expressItem.Value = expressText;

                }
                else
                {
                    throw new Exception("invalidate express");
                }
            }
            return expressItem;

        }


        public static List<ExpressItem> ExpressItems<T>(Expression<Func<T, object>>[] express) 
        {
            List<ExpressItem> list = new List<ExpressItem>();
            foreach (var item in express)
            {
                list.Add(GetExpressName(item));
            }

            
            return list;
        }


        public static ExpressItem GetExpressItem<T>(Expression<Func<T, object>> express) 
        {
            return GetExpressName<T>(express);
        }
    }
}
